﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.Collections;
using MyGeneration.dOOdads;

namespace WebUI.Controls
{
    public partial class InvoiceListCtrl : BaseListControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public bool ReadOnly
        {
            get { return ViewState[ClientID + "_ReadOnly"] != null ? (bool)ViewState[ClientID + "_ReadOnly"] : true; }
            set { ViewState[ClientID + "_ReadOnly"] = value; }
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "PrintHandler.aspx?key=" + PrintKey;
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintInvoice();
        }

        private void PrintInvoice()
        {
            try
            {
                InvoiceViewerCtrl ivcViewer = (InvoiceViewerCtrl)LoadControl(@"InvoiceViewerCtrl.ascx");
                if (hidInvoiceID.Value != "")
                    ivcViewer.LoadInvoiceByID(int.Parse(hidInvoiceID.Value));

                Session[PrintKey] = ivcViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("InvoiceListCtrl.ascx.cs", "PrintInvoice", ex.StackTrace);
            }
        }

        protected override void grid_OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            base.grid_OnItemCreated(sender, e);

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
            {
                TextBox txtBalance = e.Item.FindControl("txtBalance") as TextBox;
                Label lblBalance = e.Item.FindControl("lblBalance") as Label;

                if (lblBalance != null)
                {
                    lblBalance.Visible = ReadOnly;
                    txtBalance.Visible = !ReadOnly;
                }
            }
        }

        public void Pay(int methodID)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                if (SourceObject == null)
                    return;
                String oldFilter = SourceObject.Filter;

                Hashtable selItem = new Hashtable();
                String ids = "";

                SourceObject.Rewind();
                for (int i = 0; i < grid.Items.Count; i++)
                {
                    DataGridItem item = grid.Items[i];
                    int id = (int)grid.DataKeys[i];

                    SourceObject.Filter = "ID = " + id.ToString();
                    if (SourceObject.RowCount > 0)
                    {
                        TextBox txtBalance = item.FindControl("txtBalance") as TextBox;
                        CheckBox cbSelect = item.FindControl("cbSelect") as CheckBox;

                        if (cbSelect.Checked)
                        {
                            ids += id.ToString() + ",";
                            selItem[id] = decimal.Parse(txtBalance.Text);
                        }
                    }

                    SourceObject.MoveNext();
                }

                SourceObject.Filter = oldFilter;

                if (ids.EndsWith(","))
                    ids = ids.Remove(ids.Length - 1);

                Invoices ivc = Invoices.GetInvoiceByIDs(ids);
                InvoicePaymentHistories hist = new InvoicePaymentHistories();
                for (int i = 0; i < ivc.RowCount; i++)
                {
                    decimal amt = (decimal)selItem[ivc.ID];
                    amt = Math.Min(ivc.TotalAmount - ivc.PaidAmount, amt);
                    if (amt > 0)
                    {
                        ivc.Pay(amt, methodID, SessionUser.ID);
                        hist.AddPayment(ivc.ID, methodID, amt, DateTime.Now, SessionUser.ID);


                        if (!ivc.IsColumnNull("CustomerID") && ivc.CustomerID > 0)
                        {
                            POSSystem.BLL.Customers cust = new POSSystem.BLL.Customers();
                            cust.UpdateCustomerAmt(ivc.CustomerID, 0, amt);
                        }
                    }

                    ivc.MoveNext();
                }

                ivc.Save();
                hist.Save();
                tx.CommitTransaction();
            }
            catch(Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("InvoiceListCtrl", "Pay", ex.StackTrace);
            }
        }
    }
}